<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of StoriesController
 *
 * @author Zoila
 */
class StoriesController extends AppController{
    public $uses = array('Story','Project','ProjectTeam','MemberPoint','ProjectMember','Task','StoryComment');
    //AUTORIZACION
    public function isAuthorized($user) {
        // All registered users can add posts
        if (in_array($this->action, array('view', 'add','change','edit','poker','pokerPlanning','addTask','addComment','addPlanning'))) {
            return true;
        }

        // The owner of a post can edit and delete it
        if (in_array($this->action, array('delete'))) {
            $stId = $this->request->params['pass'][0];
            if ($this->Story->isOwnedBy($stId, $user['id'])) {
                return true;
            }
        }

        return parent::isAuthorized($user);
    }
    
    public function addTask($storyId){
        if (strcmp($this->request->data['Task']['task'],"")!=0){
            if($this->Task->save($this->request->data)){
                $this->Session->setFlash(_t('cambiosTrue'));
            }
            else{
                $this->Session->setFlash(_t('cambiosFalse'));
            }
        }
        else{
            $this->Session->setFlash(_t('cambiosFalse'));
        }
         $this->redirect(array('action'=>'view',$storyId));
    }
    public function addComment($storyId){
        if (strcmp($this->request->data['StoryComment']['text'],"")!=0){
            if($this->StoryComment->save($this->request->data)){
                $this->Session->setFlash(_t('cambiosTrue'));
            }
            else{
                $this->Session->setFlash(_t('cambiosFalse'));
            }
        }
        else{
            $this->Session->setFlash(_t('cambiosFalse'));
        }
         $this->redirect(array('action'=>'view',$storyId));
    }
    
    public function change($id,$estado,$from=''){
        $story=$this->Story->findById($id);
        $idProject=$story['Story']['project_id'];
        if ( ($story['Story']['state']==0)&&($estado==1) )
                    $story['Story']['begin']=date("Y-m-d H:i:s");
        //Cambiar fecha fin, si es necesario
        if ( ($story['Story']['state']!=$estado)&& ($estado==3) )
            $story['Story']['end']=date("Y-m-d H:i:s");
        $story['Story']['state']=$estado;
        if ($this->Story->save($story)) {
           // $this->Session->setFlash('Your userStory has been saved.');
            $this->redirect('../projects/backlogGrid/'.$idProject.'/'.$from);
        }
        else{
            $this->Session-> setFlash('Lo sentimos, ha ocurrido un error');
            $this->redirect('../projects/backlogGrid/'.$idProject.'/'.$from);
        }
        
    }
    public function people($project){
        $options['joins'] = array(    
            array('table' => 'project_teams',        
                'alias' => 'ProjectTeam',        
                'type' => 'inner',        
                'conditions' => array(            
                    'Team.id = ProjectTeam.team_id'        
                    )    
                ),    
            array('table' => 'projects',        
                'alias' => 'Project',        
                'type' => 'inner',        
                'conditions' => array(            
                    'ProjectTeam.project_id = Project.id'        
                    )    
                ));
        $options['conditions'] = array(    
            'Project.id' => $project);
        $teams = $Teams->find('all', $options);
    }
    public function add( $idProject = null,$ind=null){
        if($idProject==null){
            if(isset($this->request->data['Story']['project_id']))
                    $idProject=$this->request->data['Story']['project_id'];
        }

        if ($idProject!=null){
            if ($this->request->is('post')){  
                $this->request->data['Story']['creator_id'] = $this->Auth->user('id');
                $this->request->data['Story']['project_id'] = $idProject;
                $this->request->data['Story']['points'] = 0;
                $this->request->data['Story']['state'] = 0;
                $this->request->data['Story']['state_points'] = 0;
                if($this->Story->save($this->request->data)){
                    $this->Session->setFlash('Your userStory has been saved.');
                      switch ($ind) {
                        case(1):
                            $this->redirect(array('controller'=>'projects','action'=>'backlog',$idProject));
                            break;
                        case(2):
                            $this->redirect(array('controller'=>'projects','action'=>'backlogGrid',$idProject));
                            break;
                        case(3):
                            $this->redirect(array('controller'=>'projects','action'=>'backlogCard',$idProject));
                            break;
                        default:
                            $this->redirect(array('controller'=>'projects','action'=>'view',$idProject));
                    }

                }
                else{
                    $this->Session-> setFlash('Unable to add your story');
                }
            }
        }
        else {
            $this->set('error',true);
        }
        
    }

    public function addPlanning( ){

        if ($this->request->is('post')){
            $this->request->data['Story']['creator_id'] = $this->Auth->user('id');
            $this->request->data['Story']['points'] = 0;
            $this->request->data['Story']['state'] = 0;
            $this->request->data['Story']['state_points'] = 0;
            $this->request->data['Story']['detail'] = '';
            if($this->Story->save($this->request->data)){
                $this->layout='ajax';
                $this->render('success','ajax');
            }
            else{
                $this->layout='ayax';
                $this->render('error','ajax');
            }
        }
    }


    public function edit($id = null,$ind = null) {
            $this->view($id);
            $story=$this->Story->findById($id);

            $idPro=$story['Story']['project_id'];
            $this->Story->id = $id;
            
            if ($this->request->is('post')) {
                //Cambiar fecha de inicio, si es necesario
                if ( ($story['Story']['state']==0)&&($this->request->data['Story']['state']==1) )
                    $this->request->data['Story']['begin']=date("Y-m-d H:i:s");
                //Cambiar fecha fin, si es necesario
                if ( ($story['Story']['state']!=$this->request->data['Story']['state'])&& ($this->request->data['Story']['state']==3) )
                    $this->request->data['Story']['end']=date("Y-m-d H:i:s");
                
                if ($this->Story->save($this->request->data)) {
                    
                    $this->Session->setFlash('Your userStory has been updated.');
//                    $this->redirect(array('action'=>'view',$id));
                    switch ($ind) {
                    case(2):
                        $this->redirect(array('controller'=>'projects','action'=>'backlog',$idPro));
                        break;
                    case(3):
                        $this->redirect(array('controller'=>'projects','action'=>'backlogGrid',$idPro));
                        break;
                    case(4):
                        $this->redirect(array('controller'=>'projects','action'=>'backlogCard',$idPro));
                        break;
                    default:
                        $this->redirect(array('controller'=>'projects','action'=>'view',$idPro));
                    }     
                            
                } else {
                    $this->Session->setFlash('Unable to update your userStory.');
                }
            }
    }

    public function view($id = null,$ind = null) {
             $this->Story->bindModel(
                        array('hasMany' => array('Task','StoryComment'))
                );
            $story=$this->Story->findById($id);
            
            $idPro=$story['Story']['project_id'];
            $this->Story->id = $id;
            $i=0;
            foreach((array)$story['Task'] as $t){
                
                $story['Task'][$i] = $this->Task->findByIdAndStoryId($t['id'],$id);
                $i++;
            }
            $i=0;
            foreach((array)$story['StoryComment'] as $c){
                
                $story['StoryComment'][$i] = $this->StoryComment->findByIdAndStoryId($c['id'],$id);
                $i++;
            }
            $this->set('story',$story);

            $p_member=$this->ProjectMember->findAllByProjectId($idPro);
            $members=array();
            foreach((array)$p_member as $m){
                array_push($members,$m['User']);
            }
            $this->set('members',$members );
            $this->Project->unbindModel(
                        array('hasMany' => array('Story'),'hasAndBelongsToMany'=>array('Team'))
                );
            $this->set('project',$this->Project->findById($idPro));
            $this->refreshSession($idPro);

//            if ($this->request->is('get')) {
//                $this->request->data = $this->Story->read();
//
//            } else {
//                //Cambiar fecha de inicio, si es necesario
//                if ( ($story['Story']['state']==0)&&($this->request->data['Story']['state']==1) )
//                    $this->request->data['Story']['begin']=date("Y-m-d H:i:s");
//                //Cambiar fecha fin, si es necesario
//                if ( ($story['Story']['state']!=$this->request->data['Story']['state'])&& ($this->request->data['Story']['state']==3) )
//                    $this->request->data['Story']['end']=date("Y-m-d H:i:s");
//
//                if ($this->Story->save($this->request->data)) {
//
//                    $this->Session->setFlash('Your userStory has been updated.');
//
                    switch ($ind) {
                        case(2):
                            $this->set('return',array('controller'=>'projects','action'=>'backlog',$idPro));
                            break;
                        case(3):
                            $this->set('return',array('controller'=>'projects','action'=>'backlogGrid',$idPro));
                            break;
                        case(4):
                            $this->set('return',array('controller'=>'projects','action'=>'backlogCard',$idPro));
                            break;
                        default:
                            $this->set('return',array('controller'=>'projects','action'=>'view',$idPro));
                    }
//
//                } else {
//                    $this->Session->setFlash('Unable to update your userStory.');
//                }
//            }
    }


    public function pokerPlanning($project=null,$sprint=null){
        $all=$this->request->data['count'];
        
        $cambio=true;
        for ($i=0;$i<$all;$i++){
            $id=$this->request->data[$i]['id'];
            
            $story=$this->Story->findById($id);

            $idPro=$story['Story']['project_id'];
            $storyPoints=$this->MemberPoint->findAllByStoryIdAndUserId($id,$this->Auth->user('id'));
            if(count($storyPoints)>0){
                //UPDATEEEE

                $cambio=$this->MemberPoint->updateAll(
                    array('MemberPoint.detail'=>$this->request->data[$i]['detail'],'MemberPoint.detail'=>"'".$this->request->data[$i]['detail']."'"),
                    array('MemberPoint.user_id ='=>$this->Auth->user('id'),'MemberPoint.story_id ='=>$id)
                    );

            }
            else{
                //CREATE
                    $memberPoint= array('user_id'=> $this->Auth->user('id'),
                        'story_id'=> $id,
                        'project_id'=> $idPro,
                        'points'=> $this->request->data[$i]['points'],
                        'detail'=>$this->request->data[$i]['detail']);

                    $cambio=$this->MemberPoint->save($memberPoint);
            }
        }
        
        if ($cambio)
                $this->Session->setFlash('Se guardó poker planning.');
        else
            $this->Session->setFlash($this->request->data[0]['id']);
        
        $this->redirect(array('controller'=>'projects','action'=>'backlog',$project));
    }
    public function poker($id = null,$ind = null) {


            if ($this->request->is('get')) {
                $this->request->data = $this->MemberPoint->findByStoryIdAndUserId($id,$this->Auth->user('id'));
                $this->set('hola',$this->request->data);
            }
            else {
                $story=$this->Story->findById($id);

                $idPro=$story['Story']['project_id'];
                $cambio=true;
                $storyPoints=$this->MemberPoint->findAllByStoryIdAndUserId($id,$this->Auth->user('id'));
                if(count($storyPoints)>0){
                    //UPDATEEEE

                    $cambio=$this->MemberPoint->updateAll(
                        array('MemberPoint.points'=>$this->request->data['MemberPoint']['points']),
                        array('MemberPoint.user_id ='=>$this->Auth->user('id'),'MemberPoint.story_id ='=>$id)
                        );

                }
                else{
                    //CREATE
                      $memberPoint= array('user_id'=> $this->Auth->user('id'),
                            'story_id'=> $id,
                            'project_id'=> $idPro,
                            'points'=> $this->request->data['MemberPoint']['points'] );

                     $cambio=$this->MemberPoint->save($memberPoint);
                }
                if ($cambio)
                       $this->Session->setFlash('Se guardó poker planning.');
                else
                    $this->Session->setFlash('Error al guardar poker planning.');
                switch ($ind) {
                    case(2):
                        $this->redirect(array('controller'=>'projects','action'=>'backlog',$idPro));
                        break;
                    case(3):
                        $this->redirect(array('controller'=>'projects','action'=>'backlogGrid',$idPro));
                        break;
                    case(4):
                        $this->redirect(array('controller'=>'projects','action'=>'backlogCard',$idPro));
                        break;
                    default:
                        $this->redirect(array('controller'=>'projects','action'=>'view',$idPro));
                }
            }
    }
    
    public function delete($id,$ind) {
        
        $story=$this->Story->findById($id);
        $idPro=$story['Story']['project_id'];
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }
        if ($this->Story->delete($id)) {
            $this->Session->setFlash('The Story with id: ' . $id . ' has been deleted.');
            if ($ind == 1){
                $this->redirect(array('controller'=>'projects','action' => 'backlog',$idPro));
            }
        }
    }
    
}

?>
